package org.keco.shape;

import java.awt.BasicStroke;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Line extends AbstractShape {

	private static final long serialVersionUID = -3228260456618707102L;

	private static final Pattern PATTERN = Pattern.compile("L\\[\\(([0-9]+),([0-9]+)\\)\\(([0-9]+),([0-9]+)\\)\\]");

	private Point start;

	private Point end;

	public Line(Point start, Point end) {
		super();
		this.start = start;
		this.end = end;
		this.setLength(start.calculateDistance(end));
	}

	@Override
	public void paint(Graphics g) {
		g.setColor(getColor());

		if (g instanceof Graphics2D) {
			((Graphics2D) g).setStroke(new BasicStroke(getLineWeight()));
		}

		g.drawLine(start.getX(), start.getY(), end.getX(), end.getY());
		g.drawString(String.valueOf(getLength()), start.getX() + (end.getX() - start.getX()) / 2, start.getY() + (end.getY() - start.getY()) / 2);

		if (g instanceof Graphics2D) {
			((Graphics2D) g).setStroke(new BasicStroke(DEFAULT_LINE_WIDTH));
		}
		g.setColor(DEFAULT_COLOR);
	}

	public boolean isParallelWithCoordinates(int x1, int y1, int x2, int y2) {
		if (x1 == x2) {
			return true;
		}
		if (y1 == y2) {
			return true;
		}
		return false;
	}

	@Override
	public String toString() {
		return "L[" + start + "" + end + "]";
	}

	public static Line fromString(String value) {
		Matcher m = PATTERN.matcher(value);
		if (m.find() && m.groupCount() == 4) {
			return new Line(new Point(Integer.parseInt(m.group(1)), Integer.parseInt(m.group(2))), new Point(Integer.parseInt(m.group(3)), Integer.parseInt(m.group(4))));
		}
		return null;
	}

	public Point getStart() {
		return start;
	}

	public void setStart(Point start) {
		this.start = start;
	}

	public Point getEnd() {
		return end;
	}

	public void setEnd(Point end) {
		this.end = end;
	}

	// public boolean bellongsToLine(Point p) {
	// System.out.println((start.getY() - end.getY()) * (start.getX() -
	// p.getX()) + "==" + (start.getY() - p.getY()) * (start.getX() -
	// end.getX()));
	// return (start.getY() - end.getY()) * (start.getX() - p.getX()) ==
	// (start.getY() - p.getY()) * (start.getX() - end.getX());
	// }

	@Override
	public boolean containsPoint(Point p) {
		return start.getX() * (end.getY() - p.getY()) + end.getX() * (p.getY() - start.getY()) + p.getX() * (start.getY() - end.getY()) <= 5;
	}
}
